package jmu.edu.yjc.controller;

import jmu.edu.yjc.domain.ResponseResult;
import jmu.edu.yjc.domain.entity.Category;
import jmu.edu.yjc.domain.vo.category.CategoryVo;
import jmu.edu.yjc.service.CategoryService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

@RestController
@RequestMapping("/content/category")
public class CategoryController {
    @Resource
    private CategoryService categoryService;

    @GetMapping("/listAllCategory")
    public ResponseResult listAllCategory() {
        List<CategoryVo> categoryVos = categoryService.listAllCategory();
        return ResponseResult.okResult(categoryVos);
    }
    @PreAuthorize("@ps.hasPermission('content:category:export')")
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        categoryService.export(response);
    }

    @GetMapping("/list")
    public ResponseResult listCategory(Integer pageNum, Integer pageSize, String name, String status) {
        return categoryService.listCategory(pageNum, pageSize, name, status);
    }

    @PostMapping
    public ResponseResult addCategory(@RequestBody Category category) {
        categoryService.save(category);
        return ResponseResult.okResult();
    }

    @GetMapping("/{id}")
    public ResponseResult editCategory(@PathVariable("id") Long id) {
        return ResponseResult.okResult(categoryService.getById(id));
    }

    @PutMapping
    public ResponseResult doEditCategory(@RequestBody Category category) {
        categoryService.updateById(category);
        return ResponseResult.okResult();
    }

    @DeleteMapping("/{id}")
    public ResponseResult deleteCategory(@PathVariable("id")String id){
        String[] ids = id.split(",");
        categoryService.removeByIds(Arrays.asList(ids));
        return ResponseResult.okResult();
    }
    @PutMapping("/changeStatus")
    public ResponseResult changeCategoryStatus(@RequestBody Category category){
        categoryService.updateById(category);
        return ResponseResult.okResult();
    }
}
